<template>
  <div class="profile-container">
    <!-- 个人信息卡片 -->
    <el-card class="profile-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-avatar :size="50" src="/avatar.png" class="user-avatar" />
            <div class="user-info">
              <h2 class="user-name">{{ teacher?.name || '加载中...' }}</h2>
              <p class="user-role">{{ teacher?.college || '院系信息' }}</p>
            </div>
          </div>
          <div class="header-right">
            <el-button 
              type="primary" 
              @click="toggleEdit"
              :icon="isEditing ? 'Close' : 'Edit'"
              :loading="loading"
            >
              {{ isEditing ? '取消编辑' : '编辑信息' }}
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>

      <div v-else-if="error" class="error-container">
        <el-result
          icon="error"
          :title="error"
          sub-title="请检查网络连接或联系管理员"
        >
          <template #extra>
            <el-button type="primary" @click="loadProfile">重新加载</el-button>
          </template>
        </el-result>
      </div>

      <div v-else-if="teacher" class="profile-content">
        <el-row :gutter="24">
          <!-- 左侧：基本信息 -->
          <el-col :span="12">
            <div class="info-section">
              <div class="section-title">
                <el-icon><User /></el-icon>
                <span>基本信息</span>
              </div>
              <div class="info-grid">
                <div class="info-item">
                  <label class="info-label">姓名</label>
                  <div class="info-value">{{ teacher.name }}</div>
                </div>
                <div class="info-item">
                  <label class="info-label">工号</label>
                  <div class="info-value">{{ teacher.teacherId }}</div>
                </div>
                <div class="info-item">
                  <label class="info-label">院系</label>
                  <div class="info-value">{{ teacher.college }}</div>
                </div>
              </div>
            </div>

            <div class="info-section">
              <div class="section-title">
                <el-icon><Phone /></el-icon>
                <span>联系方式</span>
              </div>
              <el-form 
                :model="formData" 
                :rules="rules" 
                ref="contactFormRef" 
                label-width="0"
                :disabled="!isEditing"
                class="contact-form"
              >
                <el-form-item prop="mail">
                  <label class="form-label">邮箱地址</label>
                  <el-input 
                    v-model="formData.mail" 
                    placeholder="请输入邮箱地址"
                    :prefix-icon="Message"
                  />
                </el-form-item>
                <el-form-item prop="phone">
                  <label class="form-label">手机号码</label>
                  <el-input 
                    v-model="formData.phone" 
                    placeholder="请输入手机号码"
                    :prefix-icon="Phone"
                  />
                </el-form-item>
              </el-form>
            </div>
          </el-col>

          <!-- 右侧：账户信息 -->
          <el-col :span="12">
            <div class="info-section">
              <div class="section-title">
                <el-icon><Lock /></el-icon>
                <span>账户信息</span>
              </div>
              <el-form 
                :model="formData" 
                :rules="rules" 
                ref="formRef" 
                label-width="0"
                :disabled="!isEditing"
                class="account-form"
              >
                <el-form-item prop="username">
                  <label class="form-label">用户名</label>
                  <el-input 
                    v-model="formData.username" 
                    placeholder="请输入用户名"
                    :prefix-icon="User"
                  />
                </el-form-item>
                <el-form-item prop="password">
                  <label class="form-label">密码</label>
                  <el-input 
                    v-model="formData.password" 
                    type="password" 
                    show-password
                    placeholder="请输入密码"
                    :prefix-icon="Lock"
                  />
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <div v-if="isEditing" class="action-buttons">
              <el-button type="primary" @click="saveProfile" :loading="saving" size="large">
                <el-icon><Check /></el-icon>
                保存修改
              </el-button>
              <el-button @click="cancelEdit" size="large">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { User, Lock, Phone, Message, Check, Close } from '@element-plus/icons-vue';
import { getTeacherInfo, updateTeacherInfo } from '@/api/teacher';

const teacher = ref(null);
const loading = ref(false);
const saving = ref(false);
const error = ref(null);
const isEditing = ref(false);
const formRef = ref(null);
const contactFormRef = ref(null);

const formData = reactive({
  username: '',
  password: '',
  mail: '',
  phone: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名长度不能少于2位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  mail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
};

// 加载老师信息
const loadProfile = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await getTeacherInfo();
    teacher.value = response.data;
    // 填充表单数据
    Object.assign(formData, {
      username: teacher.value.username,
      password: teacher.value.password,
      mail: teacher.value.mail,
      phone: teacher.value.phone
    });
  } catch (err) {
    error.value = '加载个人信息失败';
    console.error('Failed to load profile:', err);
  } finally {
    loading.value = false;
  }
};

// 切换编辑状态
const toggleEdit = () => {
  if (isEditing.value) {
    cancelEdit();
  } else {
    isEditing.value = true;
  }
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  // 重置表单数据
  Object.assign(formData, {
    username: teacher.value.username,
    password: teacher.value.password,
    mail: teacher.value.mail,
    phone: teacher.value.phone
  });
};

// 保存个人信息
const saveProfile = async () => {
  if (!formRef.value || !contactFormRef.value) return;
  
  try {
    await Promise.all([
      formRef.value.validate(),
      contactFormRef.value.validate()
    ]);
    
    saving.value = true;
    await updateTeacherInfo(formData);
    
    ElMessage.success('个人信息更新成功');
    isEditing.value = false;
    await loadProfile();
  } catch (err) {
    if (err.message) {
      ElMessage.error(err.message);
    } else {
      ElMessage.error('保存失败，请检查表单信息');
    }
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  loadProfile();
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.user-role {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.info-section {
  margin-bottom: 24px;
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #409eff;
}

.section-title .el-icon {
  font-size: 18px;
  color: #409eff;
}

.section-title span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.info-grid {
  display: grid;
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  color: #909399;
  font-size: 14px;
}

.info-value {
  font-size: 14px;
  color: #303133;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.contact-form :deep(.el-form-item),
.account-form :deep(.el-form-item) {
  margin-bottom: 22px;
}

.contact-form :deep(.el-input__wrapper),
.account-form :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.contact-form :deep(.el-input__wrapper:hover),
.account-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.contact-form :deep(.el-input__wrapper.is-focus),
.account-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 24px;
  justify-content: flex-end;
  padding-top: 24px;
  border-top: 2px solid #409eff;
}

.action-buttons .el-button {
  padding: 12px 20px;
  font-size: 14px;
}

.loading-container,
.error-container {
  padding: 40px;
  text-align: center;
}

:deep(.el-input__prefix-icon) {
  color: #909399;
}

:deep(.el-input.is-focus .el-input__prefix-icon) {
  color: #409eff;
}
</style> 